package com.example.gkcircle.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVACL;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.example.gkcircle.App;
import com.example.gkcircle.BaseActivity;
import com.example.gkcircle.R;
import com.example.gkcircle.adapter.LostAdapter;
import com.example.gkcircle.adapter.MovieCommentAdapter;
import com.example.gkcircle.bean.Comment;
import com.example.gkcircle.bean.Lost;
import com.example.gkcircle.bean.Movie;
import com.example.gkcircle.db.DBUtil;
import com.example.gkcircle.utils.DateUtil;
import com.example.gkcircle.utils.PicUtil;
import com.example.gkcircle.utils.ToastFactory;
import com.example.gkcircle.utils.UniversalImageLoader;
import com.kyleduo.switchbutton.SwitchButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.next.tagview.TagCloudView;

/**
 * Created by Jehu on 16/4/13.
 */
public class MovieCommentActivity extends BaseActivity implements View.OnClickListener{

    private ListView mListView;
    private SwipeRefreshLayout mSwipe;
    private MovieCommentAdapter mAdapter;
    //评论回复
    private RelativeLayout mEditLayout;
    private EditText mEditText;
    private Button mCommentBtn;
    private Button mCancelBtn;
    private SwitchButton mSwitchBtn;
    private boolean isShowingEdit;
    //title bar
    private RelativeLayout mBarBg;
    private ImageButton mLeftBtn;
    private ImageButton mRightBtn;
    private TextView mRightText;
    private View mFooterView;
    //header
    private View mHearerView;
    private ImageView avatar;
    private ImageView photo;
    private ImageView footMarkImg;
    private TextView footMarkCount;
    private TextView username;
    private TextView date;
    private TextView content;
    private TextView tagView;
    private TagCloudView tagCloudView;
    private String imageUrl;
    private String thumbnailUrl;

    private final int maxPage=10;
    private int currentPage=0;
    private boolean isRefreshing;

    private List<Comment> commentList;
    private Movie movie;
    private int position;
    private boolean sex;


    @Override
    protected void initView() {
        setContentView(R.layout.love_movie_comment_activity);
        mListView=(ListView)this.findViewById(R.id.movie_comment_listview);
        mSwipe=(SwipeRefreshLayout)this.findViewById(R.id.movie_comment_swipe);
        mSwipe.setColorSchemeColors(getResources().getColor(R.color.main), getResources().getColor(R.color.love), getResources().getColor(R.color.wish));
        //title bar
        mLeftBtn = (ImageButton) this.findViewById(R.id.tabbar_left_btn);
        mRightBtn = (ImageButton) this.findViewById(R.id.tabbar_right_btn);
        mBarBg=(RelativeLayout)this.findViewById(R.id.tabbar_bg);
        mRightText=(TextView)this.findViewById(R.id.tabbar_right_text);
        //edit layout
        mEditLayout=(RelativeLayout)this.findViewById(R.id.comment_edit_layout);
        mEditText=(EditText)this.findViewById(R.id.comment_edit_edit);
        mCommentBtn=(Button)this.findViewById(R.id.comment_edit_finish_btn);
        mCancelBtn=(Button)this.findViewById(R.id.comment_edit_cancel_btn);
        mSwitchBtn=(SwitchButton)this.findViewById(R.id.comment_edit_switch);
        //footerView
        mFooterView=LayoutInflater.from(this).inflate(R.layout.comment_footer,null);
        //headerView init
        mHearerView= LayoutInflater.from(this).inflate(R.layout.love_movie_recycle_item,null);
        content=(TextView)mHearerView.findViewById(R.id.love_movie_item_content);
        photo=(ImageView)mHearerView.findViewById(R.id.love_movie_item_photo);
        tagView=(TextView)mHearerView.findViewById(R.id.love_movie_tag);
        avatar=(ImageView)mHearerView.findViewById(R.id.love_movie_item_avatar);
        username=(TextView)mHearerView.findViewById(R.id.love_movie_item_username);
        date=(TextView)mHearerView.findViewById(R.id.love_movie_item_date);
        footMarkCount=(TextView)mHearerView.findViewById(R.id.love_movie_item_footmark);
        footMarkImg=(ImageView)mHearerView.findViewById(R.id.love_movie_item_footmark_img);
        tagCloudView=(TagCloudView)mHearerView.findViewById(R.id.love_movie_cloud_tag);
        mBarBg.setBackgroundColor(getResources().getColor(R.color.main));
        mLeftBtn.setBackgroundResource(R.mipmap.back_white);
        mRightBtn.setBackgroundResource(0);
        mRightText.setText("约Ta");
        TextPaint tp=mRightText.getPaint();
        tp.setFakeBoldText(true);
        tagView.setVisibility(View.GONE);
        tagCloudView.setVisibility(View.VISIBLE);
        content.setTextSize(15);
    }

    @Override
    protected void initListener() {
        photo.setOnClickListener(this);
        mRightText.setOnClickListener(this);
        mCancelBtn.setOnClickListener(this);
        mSwitchBtn.setOnClickListener(this);
        mCommentBtn.setOnClickListener(this);
        mLeftBtn.setOnClickListener(this);
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(!isRefreshing){
                    currentPage=0;
                    isRefreshing=true;
                    setCommentData(currentPage);
                }
            }
        });
    }

    @Override
    protected void setData() {
        position=getIntent().getExtras().getInt("position");
        sex=getIntent().getExtras().getBoolean("sex");
        movie=sex?App.mMovieBoyList.get(position) : App.mMovieGirlList.get(position);
        AVUser user=movie.getUser();
        content.setText(movie.getContent());
        date.setText(movie.getCreatedAt());
        username.setText(user.get("nickname").toString());
        //用户头像
        if(null!=user.getAVFile("avatar")){
            int avatarWidth=this.getResources().getDimensionPixelSize(R.dimen.love_avatar_width);
            //获取缩略图url
            String avatarUrl=user.getAVFile("avatar").getThumbnailUrl(true,avatarWidth,avatarWidth);
            UniversalImageLoader.getIntance().displayImage(avatarUrl,avatar,UniversalImageLoader.getAvatarOptions(),UniversalImageLoader.getAnimateFirstDisplayListener());
        }else{
            avatar.setImageResource(R.mipmap.personal_default_user_icon);
        }
        //标签
        tagCloudView.setTags(movie.getTags());

        //宽 >= 高时 横向照片（3:4）
        int firstheight=(App.screenWidth -PicUtil.dip2px(this,20))*3/4;
        //宽 < 高时 竖向照片 (8:7)
        int secondHeight=(App.screenWidth-PicUtil.dip2px(this,20))*8/7;
        if(movie.getPhotoWidth()>=movie.getPhotoHeight()){
            photo.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,firstheight));
        }else{
            photo.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, secondHeight));
        }
        imageUrl=movie.getPhotoUrl();
        thumbnailUrl=movie.getThumbnailUrl();
        UniversalImageLoader.getIntance().displayImage(movie.getThumbnailUrl(), photo, UniversalImageLoader.getPhotorOptions(), UniversalImageLoader.getAnimateFirstDisplayListener());
        UniversalImageLoader.getIntance().displayImage(movie.getPhotoUrl(), photo, UniversalImageLoader.getPhotorOptions(), UniversalImageLoader.getAnimateFirstDisplayListener());

        //足迹
        footMarkCount.setText(movie.getViewCount() + "");

        //设置Adapter
        mListView.addHeaderView(mHearerView);
        mListView.addFooterView(mFooterView);
        if(App.mCommentListMap==null){
            App.mCommentListMap=new HashMap<String,List<Comment>>();
        }else{
            //如果已有缓存评论就先取出来
            commentList=App.mCommentListMap.get(movie.getObjectId());
        }
        if(commentList==null){
            commentList=new ArrayList<Comment>();;
        }
        mAdapter=new MovieCommentAdapter(MovieCommentActivity.this,commentList,movie.getCommentCount());
        mListView.setAdapter(mAdapter);
        //mAdapter=null;
        isRefreshing=true;
        //获取评论数据
        setCommentData(currentPage);
    }

    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.love_movie_item_photo:
               Intent intent=new Intent(this,PhotoViewAcitivty.class);
               Bundle bundle=new Bundle();
               bundle.putString("imageUrl",imageUrl);
               bundle.putString("thumbnailUrl",thumbnailUrl);
               intent.putExtras(bundle);
               this.overridePendingTransition(0,R.anim.zoom_in);
               startActivity(intent);
               break;
           case R.id.tabbar_right_text:
               hideEdit(false);
               break;
           case R.id.comment_edit_cancel_btn:
               hideEdit(true);
               break;
           case R.id.comment_edit_finish_btn:
               String content=mEditText.getText().toString();
               if(content.isEmpty())return;
               hideEdit(true);
               comment(content);
               break;
           case R.id.tabbar_left_btn:
               finish();
               break;

       }
    }

    private void comment(String content){
        final AVObject comment=new AVObject("MovieComment");
        comment.put("content",content);
        comment.put("user",AVUser.getCurrentUser());
        comment.put("movie", AVObject.createWithoutData("Movie", movie.getObjectId()));
        //添加权限
        AVACL acl=new AVACL();
        acl.setPublicReadAccess(true);
        //设置评论仅发布者和评论者可写
        acl.setWriteAccess(AVUser.getCurrentUser(),true);
        acl.setWriteAccess(movie.getUser(), true);
        comment.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    //更新评论数
                    final AVObject commentCount = AVObject.createWithoutData("Likes", movie.getCommentCountObjectId());
                    commentCount.setFetchWhenSave(true);
                    commentCount.increment("likeCount");
                    commentCount.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            if (e != null) return;
                            //DBUtil.getInstance(mActivity).likeWish(wish);
                            movie.setCommentCount(commentCount.getInt("commentCount"));
                            //主动刷新数据
                            mListView.setSelection(0);
                            if(!isRefreshing){
                                currentPage=0;
                                isRefreshing=true;
                                setCommentData(currentPage);
                            }
                        }
                    });

                }
            }
        });
    }

    private void setCommentData(int currentPage){
        mSwipe.setRefreshing(true);
        getComment(currentPage, new IGetDataListener() {
            @Override
            public void complete(List<AVObject> list) {

                if(isRefreshing){
                    commentList.clear();
                }
                for (int i = 0; i < list.size(); i++) {
                    Comment comment = new Comment();
                    comment.setUser(list.get(i).getAVUser("user"));
                    comment.setContent(list.get(i).get("content").toString());
                    comment.setAvObject(list.get(i).getObjectId());
                    comment.setCreatedAt(DateUtil.getLastMinTime(list.get(i).getDate("createdAt").getTime()));
                    commentList.add(comment);
                }
                App.mCommentListMap.put(movie.getObjectId(),commentList);
                mSwipe.setRefreshing(false);
                isRefreshing=false;
                if(mAdapter!=null){
                    mAdapter.notifyDataSetChanged();
                    return;
                }
                mAdapter=new MovieCommentAdapter(MovieCommentActivity.this,commentList,movie.getCommentCount());
                mListView.setAdapter(mAdapter);
            }
        });

    }

    public void getComment(int currentPage,IGetDataListener iGetDataListener){
      this.getDataListener=iGetDataListener;
        AVQuery<AVObject> query = new AVQuery<>("MovieComment");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(maxPage);
        query.setSkip(maxPage * currentPage);
        query.orderByDescending("createdAt");
        query.whereEqualTo("movie",AVObject.createWithoutData("Movie", movie.getObjectId()));
        query.include("user");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        if(dataFlag)getDataListener.complete(list);else return;
                    } else {
                        mSwipe.setRefreshing(false);
                    }
                } else {
                    mSwipe.setRefreshing(false);
                    ToastFactory.getToast(MovieCommentActivity.this, getResources().getString(R.string.connection_error)).show();
                }
            }
        });
    }

    //获取数据
    public IGetDataListener getDataListener;

    private interface IGetDataListener {
        void complete(List<AVObject> list);
    }

    private void hideEdit(boolean hide){

        if (isShowingEdit && hide) {
            isShowingEdit = false;
            mListView.setEnabled(true);
            mEditLayout.setVisibility(View.GONE);
        }else{
            isShowingEdit = true;
            mListView.setEnabled(false);
            mEditLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onBackPressed() {
        if(isShowingEdit){
            isShowingEdit=false;
            mListView.setEnabled(true);
            mEditLayout.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();
    }
}
